package com.dynamic.mybatis.core.generator.method;

import com.dynamic.mybatis.core.generator.AbstractMethod;
import com.dynamic.mybatis.core.generator.InjectorHelper;
import com.dynamic.mybatis.core.generator.MapperMethod;
import com.dynamic.mybatis.core.generator.helper.OrderByInjectorHelper;
import com.dynamic.mybatis.core.generator.helper.SelectInjectorHelper;
import com.dynamic.mybatis.core.generator.helper.WhereInjectorHelper;
import com.dynamic.mybatis.core.metadata.DynamicMappedStatement;
import com.dynamic.mybatis.core.metadata.MappedStatementTable;
import com.dynamic.mybatis.core.parser.NamespaceHelper;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.session.Configuration;

import java.util.Map;

/**
 * @Description
 * @Author xs
 * @Date 2023/4/14 10:13
 */
public class SelectList extends AbstractMethod {

    public SelectList() {
        super(MapperMethod.StandardMapperMethod.selectList);
    }

    public SelectList(MapperMethod mapperMethod) {
        super(mapperMethod);
    }

    @Override
    public String builderScriptSql(String namespace, MappedStatementTable table, MapperBuilderAssistant assistant) {
        String sql = String.format(getSqlTemplate(), InjectorHelper.sqlFirst(), SelectInjectorHelper.sqlSelectColumns(table, false), table.getTableName(),
                NEWLINE + SPACE + WhereInjectorHelper.sqlWhereWrapper(false, table), OrderByInjectorHelper.orderByDefaultKeyColumn(table), InjectorHelper.sqlComment());

        return sql;
    }

    @Override
    public DynamicMappedStatement injectMappedStatement(String tenantCode, String namespace, MappedStatementTable table, MapperBuilderAssistant assistant) {
        LanguageDriver languageDriver = assistant.getConfiguration().getDefaultScriptingLanguageInstance();
        Configuration configuration = assistant.getConfiguration();
        String sql = builderScriptSql(namespace, table, assistant);

        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, Map.class);
        String msNamespace = NamespaceHelper.getNamespace(tenantCode,namespace);

        MappedStatement ms = super.addMappedStatement(assistant, table, msNamespace, sqlSource, SqlCommandType.SELECT, Map.class, null, Map.class, NoKeyGenerator.INSTANCE, null, null);

        return builderDynamicMappedStatement(tenantCode, namespace, table, ms, sql);
    }
}